package cn.witque.service.impl;

import cn.witque.pojo.ItripUser;
import cn.witque.service.TokenSevice;
import cn.witque.utils.AgentUtil;
import cn.witque.utils.Md5Util;
import com.alibaba.fastjson.JSONArray;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @author jyk
 */
@Service
public class TokenServiceImpl implements TokenSevice {

    @Resource
    private RedisTemplate redisTemplate;

    //多少分钟的Token有效期
    public static Integer MINUTE = 21600;
    //token保护时间
    public static Integer REPLACE_MINUTE = 1;
    /**
     * 创建token
     * @param agent
     * @param user
     * @return token：用户设备-用户名的Md5-日期格式化
     */
    @Override
    public String createToken(String agent, ItripUser user) {
        String prefix = "token:";
        String userMachine  = AgentUtil.getUserMachine(agent);
        StringBuilder sb = new StringBuilder();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        sb.append(prefix);
        sb.append(userMachine+"-");
        sb.append(Md5Util.getMd5(user.getUserCode(),10)+"-");
        sb.append(simpleDateFormat.format(new Date()));
        return sb.toString();

    }

    /**
     * 将token保存在redis里面
     * @param token
     * @param user
     */
    @Override
    public void saveToken(String token, ItripUser user) {
        if (token.indexOf("Android") != -1 || token.indexOf("IPhone") != -1){
            redisTemplate.opsForValue().set(token,user);
        }else {
            redisTemplate.opsForValue().set(token,user,MINUTE,TimeUnit.MINUTES);
        }
    }


    /**
     * 用户注销
     * @param token
     */
    @Override
    public void deleteToken(String token) {
        if(redisTemplate.hasKey(token)) {
            redisTemplate.delete(token);
        }
    }


    /**
     * token校验
     * @param agent
     * @param token
     * @return
     */
    @Override
    public boolean validate(String agent, String token) {
            if (!redisTemplate.hasKey(token)) {
            return false;
            }
            String prefix = token.split("-")[0];
            String loaclAgent = prefix.split(":")[1];
            if (!loaclAgent.equals(agent)){
                return false;
            }
            return true;
    }


    /**
     * 根据token读取User对象
     * @param token
     * @return
     */
    @Override
    public ItripUser readToken(String token) {
        return (ItripUser) redisTemplate.opsForValue().get(token);
    }

    /**
     * 置换token
     * @param agent
     * @param token
     * @return
     */

    @Override
    public String replaceToken(String agent, String token) throws ParseException {
            if (!redisTemplate.hasKey(token)){
                throw new RuntimeException("Token不存在，或者已经过期了！");
            }

            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
            Date tokenTime = simpleDateFormat.parse(token.split("-")[2]);
            long currentTime = Calendar.getInstance().getTimeInMillis();
            long differTime = currentTime - tokenTime.getTime();

            if (differTime < REPLACE_MINUTE * 60 * 1000){
                throw new RuntimeException("token保护时间不予置换");
            }
            ItripUser user = this.readToken(token);
            long expire = redisTemplate.getExpire(token);
            String newToken = "";
            if (expire == -1 || expire > 0){
                newToken = createToken(agent,user);
                this.saveToken(newToken,user);
                redisTemplate.opsForValue().set(token,user,5,TimeUnit.MINUTES);
            }else{
                throw new RuntimeException("token时间异常");
            }
            return newToken;
    }


}
